<template>
  <q-page class="q-pa-md">

<!--    fill-input  -->
    <q-form @submit.prevent="addQuery">



      <q-checkbox v-model="showSelects" label="最大负荷" class="q-mb-md"></q-checkbox>
      <q-select
        v-if="showSelects"
        v-model="queryInput"
        :options="filteredOptions"
        label="最大负荷"
        use-input

        input-debounce="500"
        @filter="filterOptions"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>

<!--select * from line left join operate on line.linename = operate.operatelinename where line.linename = queryInput-->


      <q-select
        v-model="queryInput2"
        :options="filteredOptions2"
        label="operatemission"
        use-input

        input-debounce="500"
        @filter="filterOptions2"
        dense
        filled
        class="q-mb-md"
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey">
              无匹配内容
            </q-item-section>
          </q-item>
        </template>
      </q-select>





      <q-btn type="submit" label="查询" color="primary" class="q-ml-md" />
    </q-form>


    <div v-if="queries.length">
      <h3>查询内容</h3>
      <div>
        <q-chip
          v-for="(query, index) in queries"
          :key="index"
          removable
          @remove="removeQuery(index)"
          class="q-mr-md q-mb-md"
        >
          {{ query }}
        </q-chip>
      </div>
    </div>

<!--   加入组件-->

    <!-- 搜索组件显示 -->
    <div class="q-pa-md">
      <div class="q-pa-md row q-gutter-x-md">
        <div class="col">
          <q-select
            v-model="selectedColumns"
            multiple
            :options=columns
            label="选择要显示的列"
          />
        </div>
        <div class="col">
          <q-input dense filled v-model="searchQuery" label="输入搜索内容..."></q-input>
        </div>
        <div class="col-auto">

          <q-btn dense rounded color="primary" icon="search" label="搜索" @click="searchData"></q-btn>
        </div>
      </div>
      <q-btn label="Export to Excel" color="primary" @click="exportToExcel" />

      <q-table :data="querySearchResult" :columns="filteredColumns" flat binary-state-sort class="q-mt-md"></q-table>

    </div>

<!--    加入组件结束-->

    <div v-if="result">
      <h3>查询结果</h3>
      <p>{{ result }}</p>
    </div>
  </q-page>
</template>

<script>
import * as XLSX from 'xlsx';
import axios from 'axios';
export default {
  data() {
    return {

      searchQuery:'',
      columns2:[],
      selectedColumns2: [], // 用户选择显示的列名数组
      filteredOptions2: [],  // 过滤后的选项
      ywNames2:'',
      queryInput2: '',
      queries2: [],
      result2: '',
      querySearchResult2:[],

      columns:[],
      showSelects: false, // 控制 q-select 显示的状态
      selectedColumns: [], // 用户选择显示的列名数组
      filteredOptions: [],  // 过滤后的选项
      ywNames:'',
      queryInput: '',
      queries: [],
      result: '',
      querySearchResult:[],
    };
  },
  computed:{
    filteredColumns() {
      return this.selectedColumns;
    },
    filteredColumns2() {
      return this.selectedColumns2;
    },
  },
  methods: {
    searchData(){},
    filterOptions(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptions = this.ywNames.filter(v => v.match(filter))
        } else {
          this.filteredOptions = this.ywNames
        }
      });
    },
    filterOptions2(val, update) {
      update(() => {
        if (val) {
          const filter = new RegExp(val, 'i')
          this.filteredOptions2 = this.ywNames2.filter(v => v.match(filter))
        } else {
          this.filteredOptions2 = this.ywNames2
        }
      });
    },
    addQuery() {
      if (this.queryInput) {
        this.queries.push(this.queryInput);

        this.search();
        // this.queryInput = '';
      }
    },
    removeQuery(index) {

      this.queries.splice(index, 1);
      this.search();
    },
    searchQuery_native(){
      console.log("------------------")
    },
   buildElasticsearchQuery(queryInput, operatemission) {
      const mustClauses = [];

      // 始终检查'linename'字段
      mustClauses.push({
        "match_phrase": {
          "linename": queryInput
        }
      });

      // 如果operatemission有值，也检查'description'字段
      if (operatemission) {
        mustClauses.push({
          "match_phrase": {
            "operatemission": operatemission
          }
        });
      }

      // 构建查询JSON
      const query = {
        "query": {
          "bool": {
            "must": mustClauses
          }
        }
      };

      return query;
    },
    exportToExcel() {
          const data = this.querySearchResult.map(row => {
            const rowData = {};
            this.filteredColumns.forEach(column => {
              rowData[column.label] = row[column.field];
            });
            return rowData;
          });

          const ws = XLSX.utils.json_to_sheet(data);
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, "Results");
          XLSX.writeFile(wb, "export.xlsx");
        },
    async search() {
      console.log("========search=======")
      var queryString  = this.buildElasticsearchQuery(this.queryInput, this.queryInput2);
      console.log(queryString)
      // 发送查询请求
      const response = await axios.post(
        'http://43.136.220.136:9002/sqlgen/_search'
        ,queryString,
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + btoa('admin:1992A1573')
          }
        }
      );
      console.log("-----------------------")
      console.log(response)

      this.searchResults = response.data.hits.hits.map(hit => hit._source);
      // 处理响应数据
      if (this.searchResults.length > 0) {
        this.columns = Object.keys(this.searchResults[0]).map(key => ({
          name: key,
          label: key, // 可以在这里将 key 转换为更友好的标签
          field: key,
          align: 'left',
          sortable: true
        }));
      }
      this.querySearchResult = this.searchResults

      // data.push({"key":hits[0].key+"-"+hits2[0].key,"value":hits[0].doc_count})

    //   try {
    //     // 发送 GET 请求并等待响应
    //     // 将条件传过去就ok了 当前输入数组内容作为参数传入。
    //     console.log(this.queries)
    //     const response = await axios.get('http://127.0.0.1:4444/get_xiangtongyongtu_names', {
    //     params: { items_yw: JSON.stringify(this.queries) }  // 确保键名与后端匹配
    //   });
    //     // 处理成功情况
    //
    //     console.log('Road names:', response.data.road_names);
    //     this.result = `当前查询结果: ${JSON.stringify({"所属光缆":response.data[0]['所属光缆'],"统计值":response.data[0]['数量']})}`;
    //     localStorage.setItem('渲染',JSON.stringify(response.data[0]))
    //
    //     return ;
    // } catch (error) {
    //     // 处理错误情况
    //     console.error('Error fetching data:', error);
    // }

      // console.log("search")
      // const uniqueItems = {};
      // const data = [];
      // var queriesq = []
      // console.log(this.queries)
      //
      // for (const query1 of this.queries) {
      //   queriesq = []
      //   queriesq.push(query1)
      //     console.log(query1)
      //     if (queriesq.length>0) {
      //     if (!queriesq.includes("SDH")) {
      //           queriesq.push("SDH");
      //         }
      //     // 构建查询条件
      //     const mustQueries = queriesq.map(condition => ({
      //       match_phrase: {
      //         "对应光路": condition
      //       }
      //     }));
      //
      //     // 构建最终查询
      //     const query = {
      //       bool: {
      //         must: mustQueries
      //       }
      //     };
      //
      //     try {
      //       // 发送查询请求
      //       const response = await axios.post(
      //         'http://43.136.220.136:9002/xianmen_guanglu/_search',
      //         {
      //           query: query,
      //          "size": 0,
      //           "aggs": {
      //             "by_belonging_cable": {
      //               "terms": {
      //                 "field": "所属光缆.keyword"
      //               },
      //               "aggs": {
      //                 "unique_routes": {
      //                   "cardinality": {
      //                     "field": "对应光路.keyword"
      //                   }
      //                 }
      //               }
      //             },
      //             "by_route": {
      //               "terms": {
      //                 "field": "对应光路.keyword"
      //               },
      //               "aggs": {
      //                 "unique_cables": {
      //                   "cardinality": {
      //                     "field": "所属光缆.keyword"
      //                   }
      //                 }
      //               }
      //             }
      //           }
      //         },
      //         {
      //           headers: {
      //             'Content-Type': 'application/json',
      //             'Authorization': 'Basic ' + btoa('admin:1992A1573')
      //           }
      //         }
      //       );
      //
      //       // 处理响应数据
      //       const hits = response.data.aggregations.by_belonging_cable.buckets;
      //       const hits2 = response.data.aggregations.by_route.buckets;
      //       const result = hits[0].key;
      //       data.push({"key":hits[0].key+"-"+hits2[0].key,"value":hits[0].doc_count})
      //
      //     } catch (error) {
      //       console.error("查询失败:", error);
      //       this.result = '查询失败';
      //     }
      //   } else {
      //     this.result = '暂无查询内容';
      //   }
      // }
      //
      //  this.result = `当前查询结果: ${JSON.stringify(data)}`;

    }
  },
  async mounted() {

    // 发送查询请求
    const response = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_maxload": {
            "terms": {
              "field": "maxload",
              "size": 10000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response)
    // 处理响应数据
    const hits = response.data.aggregations.unique_maxload.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    const keys = hits.map(hit => hit.key);
    this.ywNames = keys
    console.log(keys)
    // ------------------------------------------------------------------------
    // data.push({"key":hits[0].key+"-"+hits2[0].key,"value":hits[0].doc_count})





    // -------------------------第二个参数-----------------------------------------------

    // 发送查询请求
    const response2 = await axios.post(
      'http://43.136.220.136:9002/sqlgen/_search',
      {
        "size": 0,
        "aggs": {
          "unique_operatemission": {
            "terms": {
              "field": "operatemission.keyword",
              "size": 10000
            }
          }
        }
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        }
      }
    );
    console.log(response2)
    // 处理响应数据
    const hits2 = response2.data.aggregations.unique_operatemission.buckets;
    // 将这里下边的所有json中的key取出来组成一个数组
    const keys2 = hits2.map(hit => hit.key);
    this.ywNames2 = keys2
    console.log(keys2)





  }

};
</script>
